package com.ezcolour.ticket.web.global;

import com.ezcolour.ticket.dao.VocalBeanDao;
import com.ezcolour.ticket.model.VocalBean;
import com.ezcolour.ticket.service.VocalBeanService;
import com.ezcolour.ticket.util.SpringContextHolder;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@Component
@DependsOn("springContextHolder")
public class GlobalCache {


    private VocalBeanDao vocalBeanDao = SpringContextHolder.getBean(VocalBeanDao.class);


    public static ConcurrentHashMap<String,ConcurrentHashMap<String,String>> user_auto_all = new ConcurrentHashMap<>();
    //登录成功的cookie
    public static ConcurrentHashMap<String,ConcurrentHashMap<String,CookieStore>> user_login_cookies = new ConcurrentHashMap<>();
    //登录中cookie
    public static ConcurrentHashMap<String,ConcurrentHashMap<String,CookieStore>> user_cookies = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String,ConcurrentHashMap<String,HttpResponse>> user_qrcode = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String,ConcurrentHashMap<Long,VocalBean>> user_vocal = new ConcurrentHashMap<>();

    public static GlobalCache me() {
        return SpringContextHolder.getBean("globalCache");
    }

    public ConcurrentHashMap<Long, VocalBean> getOrderByCache(String username){
        ConcurrentHashMap<Long, VocalBean> ordersMap = user_vocal.get(username);
        if(ordersMap==null || ordersMap.size()<=0){
            ordersMap = new ConcurrentHashMap<Long, VocalBean>();
            System.out.println("缓存为空");
            List<VocalBean> orderList = vocalBeanDao.findByUsernameAndStatu(username,1);
            for (VocalBean vo:
                    orderList) {
                System.out.println("空的时候添加"+vo.getId());
                ordersMap.put(vo.getId(),vo);
            }
            if(ordersMap!=null && ordersMap.size()>0){
                user_vocal.put(username,ordersMap);
            }
        }
        return ordersMap;
    }

    public void setUserVocalMap(){
        user_vocal.clear();
        List<VocalBean> orderList = vocalBeanDao.findAllByStatu(1);
        List<String> usernameList = new ArrayList<>();
        for (VocalBean vo:
                orderList) {
            ConcurrentHashMap<Long, VocalBean> ordersMap;
            if(usernameList.contains(vo.getUsername())){
                ordersMap = user_vocal.get(vo.getUsername());

            }else{
                usernameList.add(vo.getUsername());
                ordersMap = new ConcurrentHashMap<>();
            }
            ordersMap.put(vo.getId(),vo);
            user_vocal.put(vo.getUsername(),ordersMap);
        }
    }
}
